//
//  ToolObject.m
//  WuYeUser
//
//  Created by Saxon on 2018/3/22.
//  Copyright © 2018年 com.WuyeUser.remotevillage. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "SJToolObject.h"

@implementation SJToolObject

+ (void)checkVersionForcedUpdate:(BOOL)forcedUpdate
{
    return;
    
    NSDate *lastDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"SJLastUpdateTime"];
    NSDate *nowDate = [NSDate date];
    if (lastDate && lastDate.timeIntervalSince1970 + 86400 >= nowDate.timeIntervalSince1970) {
        return;
    }
    
    
    
    
    NSString *bundleIdentifier =  [NSBundle mainBundle].bundleIdentifier;
    
    NSString *iTunesServiceURL = [NSString stringWithFormat:@"https://itunes.apple.com/CN/lookup?bundleId=%@", bundleIdentifier];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:iTunesServiceURL]
                                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                         timeoutInterval:20];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]  completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSInteger statusCode = ((NSHTTPURLResponse *)response).statusCode;
        if (statusCode == 200) {
            //in case error is garbage...
            NSError *error = nil;
            
            id json = nil;
            if ([NSJSONSerialization class])
            {
                json = [[NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingOptions)0 error:&error][@"results"] lastObject];
            }
            else
            {
                //convert to string
                json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            }
            
            NSString *newVersion = @"", *trackViewUrl = @"", *releaseNotes = @"";
            if ([[json objectForKey:@"bundleId"] isEqualToString:bundleIdentifier]) {
                newVersion = [json objectForKey:@"version"];
                trackViewUrl = [json objectForKey:@"trackViewUrl"];
                releaseNotes = [json objectForKey:@"releaseNotes"];
            } else {
                return;
            }
            //获取本地软件的版本号
            NSString *localVersion = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleVersion"];
            
            if ([newVersion compare:localVersion options:NSNumericSearch] == NSOrderedDescending)
            {
                UIViewController *topController = [UIApplication sharedApplication].delegate.window.rootViewController;
                while (topController.presentedViewController)
                {
                    topController = topController.presentedViewController;
                }
                
                if ([UIAlertController class] && topController)
                {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"发现新版本(V%@)！", newVersion] message:releaseNotes preferredStyle:UIAlertControllerStyleAlert];
                    
//                    if (!forcedUpdate) {
                        //remind action
                        [alert addAction:[UIAlertAction actionWithTitle:@"下次再说" style:UIAlertActionStyleCancel handler:^(__unused UIAlertAction *action) {
                            [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"SJLastUpdateTime"];
                        }]];
//                    }
                    //download/ok action
                    [alert addAction:[UIAlertAction actionWithTitle:@"下载更新" style:UIAlertActionStyleDefault handler:^(__unused UIAlertAction *action) {
                        NSURL *url = [NSURL URLWithString:trackViewUrl];
                        if ([[UIApplication sharedApplication] canOpenURL:url]) {
                            [[UIApplication sharedApplication] openURL:url];
                        }
                    }]];
                    //get current view controller and present alert
                    [topController presentViewController:alert animated:YES completion:NULL];
                 
                    
                    for (UIView *view in alert.view.subviews) {
                        NSLog(@"view:%@", view);
                    }
                }
                
            }
            
        }
    }];
}
+ (BOOL)buildForDevelop
{
#ifdef DDXQ_BUILD_FOR_DEVELOP
    return true;
#else
    return false;
#endif
}
+ (float)roundFloat:(float)price
{
    NSString *temp = [NSString stringWithFormat:@"%.7f",price];
    NSDecimalNumber *numResult = [NSDecimalNumber decimalNumberWithString:temp];
    NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler
                                       decimalNumberHandlerWithRoundingMode:NSRoundBankers
                                       scale:2
                                       raiseOnExactness:NO
                                       raiseOnOverflow:NO
                                       raiseOnUnderflow:NO
                                       raiseOnDivideByZero:YES];
    return [[numResult decimalNumberByRoundingAccordingToBehavior:roundUp] floatValue];
}
@end
